package com.wechat.service.account.util;

import com.alibaba.fastjson.JSONObject;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.wechat.service.account.dto.customMenu.GetMessageEventReqDTO;
import com.wechat.service.account.dto.customMenu.MenuEventBaseDTO;
import com.wechat.service.account.dto.messageManage.replyUserMessage.ReplyImageTextItem;
import com.wechat.service.account.dto.messageManage.replyUserMessage.ReplyImageTextMessageDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;


/**
 * @author： ygl
 * @date： 2019/07/11
 * @Description：
 */
@Slf4j
public class XmlUtil {

    /**
     * bean转成微信的xml消息格式
     * @param object
     * @return
     */
    public static String beanToXml( Object object) {
        XStream xStream = new XStream(new DomDriver());
        xStream.alias("xml", object.getClass());
        xStream.processAnnotations(object.getClass());
        String xml = xStream.toXML(object);
        if (!StringUtils.isEmpty(xml)){
            return xml;
        }else{
            return null;
        }
    }


    /**
     * 图文微信的xml消息格式
     * @param object
     * @return
     */
    public static String imageTextToXml(ReplyImageTextMessageDTO object) {
        XStream xStream = new XStream(new DomDriver());
        xStream.alias("xml", ReplyImageTextMessageDTO.class);
        xStream.alias("item", ReplyImageTextItem.class);
        xStream.processAnnotations(object.getClass());
        String xml = xStream.toXML(object);
        if (!StringUtils.isEmpty(xml)){
            return xml;
        }else{
            return null;
        }
    }

    /**
     * xml转成bean泛型方法
     * @param resultXml
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T xmlToBean(String resultXml, Class clazz) {
        try {
            // XStream对象设置默认安全防护，同时设置允许的类
            XStream stream = new XStream(new DomDriver());
            XStream.setupDefaultSecurity(stream);
            stream.allowTypes(new Class[]{clazz});
            stream.processAnnotations(new Class[]{clazz});
            stream.setMode(XStream.NO_REFERENCES);
            stream.alias("xml", clazz);
            return (T) stream.fromXML(resultXml);
        } catch (Exception e){
            log.error("!!!!!!xmlToBean error:{}!!!!!!",e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        // bean 转 xml
        MenuEventBaseDTO dto = new MenuEventBaseDTO();
        dto.setFromUserName("from");
        dto.setToUserName("to");
        dto.setCreateTime(System.currentTimeMillis());
        dto.setEvent("CLICK");
        dto.setEventKey("key");
        dto.setMsgType("TEXT");
        String xml = beanToXml(dto);
        System.out.println(xml);

        // xml 转 bean
        GetMessageEventReqDTO obj = xmlToBean(xml, GetMessageEventReqDTO.class);
        System.out.println(JSONObject.toJSONString(obj));
    }


}
